<template>
  <van-form @submit="onSubmit">
    <van-cell-group inset>
      <van-field
          show-word-limit
          maxlength="20"
          v-model="team.teamName"
          name="teamName"
          label="名称"
          placeholder="请输入"
          :rules="[{ required: true, message: '请填写名称' }]"
      />
      <van-field
          show-word-limit
          maxlength="400"
          autosize
          rows="3"
          type="textarea"
          v-model="team.teamDescription"
          name="teamDescription"
          label="描述"
          placeholder="请输入"
          :rules="[{ required: true, message: '请填写描述' }]"
      />
      <van-field name="maxNum" label="人数">
        <template #input>
          <van-stepper min="3" max="10" v-model="team.maxNum"/>
        </template>
      </van-field>
      <van-field name="teamStatus" label="类型" :rules="[{ required: true, message: '请选择类型' }]">
        <template #input>
          <van-radio-group v-model="team.teamStatus" direction="horizontal">
            <van-radio name="0">公开</van-radio>
            <van-radio name="1">加密</van-radio>
          </van-radio-group>
        </template>
      </van-field>
      <van-field v-if="iniTeamStatus == 1 && team.teamStatus == 1" name="teamStatus" label="是否更改密码" :rules="[{ required: true, message:
      '请选择' }]">
        <template #input>
          <van-radio-group v-model="ifChangePwd" direction="horizontal">
            <van-radio name="1">是</van-radio>
            <van-radio name="0">否</van-radio>
          </van-radio-group>
        </template>
      </van-field>
      <van-field
          v-if="ifChangePwd == 1 && iniTeamStatus == 1 && team.teamStatus == 1"
          v-model="team.oldPassword"
          type="password"
          name="oldPassword"
          label="旧密码"
          placeholder="请输入"
          :rules="[{ required: true, message: '请填写旧密码' },
                     {
                        pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{8,10}$/,
                        message: '密码必须包含大小写字母和数字的组合，不能使用特殊字符，长度在8-10之间',
                     }]"
      />
      <van-field
          v-if="ifChangePwd == 1 && iniTeamStatus == 1 && team.teamStatus == 1"
          v-model="team.newPassword"
          type="password"
          name="newPassword"
          label="新密码"
          placeholder="请输入"
          :rules="[{ required: true, message: '请填写新密码' },
                     {
                        pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{8,10}$/,
                        message: '密码必须包含大小写字母和数字的组合，不能使用特殊字符，长度在8-10之间',
                     }]"
      />
      <van-field
          v-if="(iniTeamStatus == 0 && team.teamStatus == 1) || (!iniTeamStatus && team.teamStatus == 1)"
          v-model="team.teamPassword"
          type="password"
          name="teamPassword"
          label="密码"
          placeholder="请输入"
          :rules="[{ required: true, message: '请填写密码' },
                     {
                        pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{8,10}$/,
                        message: '密码必须包含大小写字母和数字的组合，不能使用特殊字符，长度在8-10之间',
                     }]"
      />
      <van-field
          v-model="team.expireTime"
          is-link
          readonly
          name="expireTime"
          label="截止时间"
          placeholder="点击选择"
          @click="show = true"
          :rules="[{ required: true, message: '请选择截止时间' }]"
      />
      <van-calendar :show-title="false" v-model="team.expireTime" :min-date="minDate" :max-date="maxDate"
                    v-model:show="show"
                    @confirm="onConfirm"/>
    </van-cell-group>
    <div style="margin: 16px;">
      <van-button round block type="primary" native-type="submit">
        提交
      </van-button>
    </div>
  </van-form>
</template>

<script setup lang="ts">
import {onMounted, ref} from "vue";
import {closeToast, showLoadingToast} from "vant/es";
import myAxios from "../plugins/myAxios";
import {showSuccessToast} from "vant/lib/toast/function-call";
import {useRoute, useRouter} from "vue-router";

const iniTeamStatus = ref(null);
const ifChangePwd = ref("0");
const date = ref(null);
const minDate = new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate() + 1);
const maxDate = new Date(2210, 0, 31);
const show = ref(false);
const formatDate = (date) => `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()} 00:00:00`;
const onConfirm = (value) => {
  show.value = false;
  date.value = value;
  team.value.expireTime = formatDate(value) as any;
};
const initTeam = {
  "id": null,
  "teamName": "",
  "teamDescription": null,
  "expireTime": null,
  "maxNum": 3,
  "teamPassword": "",
  "teamStatus": null,
  "oldPassword": "",
  "newPassword": "",
  "userId": null,
};
const team = ref(initTeam);
const router = useRouter();
const onSubmit = async () => {
  showLoadingToast({message: '加载中...', forbidClick: true, duration: 0});
  let expireTime = new Date(new Date(date.value).getTime() + 8 * 60 * 60 * 1000); // 加八小时
  team.value.expireTime = expireTime as any;
  const createUrl = '/team-manage/create';
  const updateUrl = '/team-manage/edit';
  const response = await myAxios.post(id ? updateUrl : createUrl, team.value) as any;
  closeToast();
  if (response) {
    router.back();
    showSuccessToast(id ? '修改成功' : '创建成功');
  }
};
const route = useRoute();
const id = route.query.teamId;
onMounted(async () => {
  if (id) {
    const res = await myAxios.post('/team-manage/get', {
      id: id
    });
    if (res) {
      iniTeamStatus.value = res.data.teamStatus;
      date.value = format(res.data.expireTime) as any;
      team.value = {
        ...res.data,
        teamStatus: res.data.teamStatus.toString(),
        expireTime: new Date(res.data.expireTime).toLocaleString()
      }
    }
  }
});
const format = (dateStr: string) => {
  const date = new Date(dateStr);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds} GMT+0800 (中国标准时间)`;
}
</script>
